<!-- 用户管理模块 -->
<template>
  <div class="">
    <el-card style="margin-bottom: 5px">
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="addUser" size="mini" v-has="'add'"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <yg-table
        :columns="columns"
        :tableList="TableList"
        :loading="loadingShow"
      >
        <el-table-column slot="action" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="warning" icon="el-icon-key" circle @click="updateUserPassword(scope.row)" size="mini"></el-button>
            <el-button type="primary" icon="el-icon-edit" circle @click="editUser(scope.row)" size="mini" v-has="'edit'"></el-button>
            <el-button type="danger" icon="el-icon-delete" slot="reference" circle @click="delectUser(scope.row)" size="mini" v-has="'del'"></el-button>
          </template>
        </el-table-column>
      </yg-table>
    </el-card>
    <!-- 添加用户弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addUserDialogClose"
      :close-on-click-modal="false"
    >
      <yg-from
        ref="addForm"
        :formObj="adduserFromObj"
        :formData="adduserFromData"
      ></yg-from>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addUserDialogVisible = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="addUserConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改用户信息 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="editUserDialogClose"
      :close-on-click-modal="false"
    >
      <yg-from
        ref="editForm"
        :formObj="edituserFromObj"
        :formData="edituserFromData"
      ></yg-from>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editUserDialogVisible = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="editUserConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改用户密码 -->
    <el-dialog
      title="修改用户密码"
      :visible.sync="updateUserDialogVisible"
      width="50%"
      @close="updateUserDialogClose"
      :close-on-click-modal="false"
    >
      <yg-from
        ref="updateForm"
        :formObj="updatePasswordFromObj"
        :formData="updatePasswordFromData"
      ></yg-from>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="updateUserDialogVisible = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="updateUserConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { myStorage } from "@/utils/localStorage";
import YgTable from "@/components/Table/YgTable.vue";
import YgFrom from "@/components/Form/YgFrom.vue";
import {
  setMessageCallback,
  publishMsg,
  removeMessageCallback,
  checkSpecialId,
} from "@/mqtt";
import md5 from "js-md5";
let Base64 = require("js-base64").Base64;
export default {
  //import引入的组件需要注入到对象中才能使用
  name: "ParamUser",
  components: {
    YgTable,
    YgFrom,
  },
  data() {
    let validateNewPassword = (rule, value, callback) => {
      if (value === this.updatePasswordFromData.oldPassword) {
        callback(new Error("新密码不能与旧密码相同"));
      } else {
        callback();
      }
    };
    const validateTel = (rule, value, callback) => {
      const regexp = /^(\+\d{2,3}-)?\d{11}$/;
      if (!regexp.test(value)) {
        callback(new Error("请输入正确的号码格式"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      loadingShow: false, //加载表格数据
      addUserDialogVisible: false, //添加用户弹窗显隐
      editUserDialogVisible: false, //修改用户信息
      updateUserDialogVisible: false, //更新用户密码
      columns: [
        // {index:true},
        {
          prop: "username",
          label: "登录名",
          align: "left",
        },
        {
          prop: "nickname",
          label: "姓名",
        },
        {
          prop: "limits",
          label: "用户角色",
          formatter(row) {
            if (row.hasOwnProperty("limits")) {
              return row.limits == 0 ? "管理员" : "普通用户";
            } else {
              return "";
            }
          },
        },
        {
          prop: "cellphone",
          label: "手机号",
        },
        {
          prop: "isLogin",
          label: "登录状态",
          formatter(row) {
            if (row.hasOwnProperty("isLogin")) {
              return (row.isLogin = true ? "上线" : "离线");
            } else {
              return "";
            }
          },
        },
        {
          prop: "lastLogin",
          label: "最后一次登录时间",
        },
        {
          prop: "lastLogout",
          label: "最后一次登出时间",
        },
        { slot: "action", align: "center" },
      ],
      TableList: [],
      formObj: [
        {
          input: true, //是input
          label: "登录名称", //字段
          prop: "username", //字段名
          placeholder: "可模糊搜索", //提示内容
          width: 5, //参考el-col
          disabled: false, //是否禁用
          labelWidth: "80px",
        },
        {
          select: true,
          label: "登录状态",
          prop: "isLogin",
          placeholder: "请选择类型",
          width: 5, //参考el-col
          disabled: false,
          clearable: true, //是否清空
          labelWidth: "80px",
          options: [
            { label: "上线", value: true },
            { label: "离线", value: false },
          ],
        },
        {
          button: true,
          label: "",
          prop: "queryButton",
          placeholder: "查询",
          width: 1.5, //参考el-col
          disabled: false,
          buttonType: "success",
          icon: "el-icon-search",
        },
        {
          button: true,
          label: "",
          prop: "resetButton",
          placeholder: "重置",
          width: 1, //参考el-col
          disabled: false,
          buttonType: "danger",
          icon: "el-icon-refresh",
        },
      ],
      formData: {
        username: "",
        isLogin: "",
      },
      adduserFromObj: [
        {
          input: true, //是input
          label: "登录名称", //字段
          prop: "username", //字段名
          width: 12, //参考el-col
          placeholder: "请输入登录名称",
          disabled: false, //是否禁用
          labelWidth: "80px",
          rules: [
            {
              required: true,
              message: "请输入登录名称",
              trigger: "blur",
            },
          ],
        },
        {
          input: true, //是input
          label: "用户名称", //字段
          prop: "nickname", //字段名
          width: 12, //参考el-col
          placeholder: "请输入用户名称",
          disabled: false, //是否禁用
          labelWidth: "80px",
        },
        {
          input: true, //是input
          label: "手机号", //字段
          prop: "cellphone", //字段名
          width: 12, //参考el-col
          placeholder: "请输入手机号",
          disabled: false, //是否禁用
          labelWidth: "80px",
        },
        {
          input: true, //是input
          label: "用户密码", //字段
          prop: "password", //字段名
          width: 12, //参考el-col
          placeholder: "请输入密码",
          disabled: false, //是否禁用
          labelWidth: "80px",
          rules: [
            {
              required: true,
              message: "请输入用户密码",
              trigger: "blur",
            },
          ],
        },
        {
          select: true,
          label: "用户角色",
          prop: "limits",
          placeholder: "请选择用户角色",
          width: 12, //参考el-col
          disabled: false,
          clearable: true, //是否清空
          labelWidth: "80px",
          options: [
            { label: "管理员", value: 0 },
            { label: "普通用户", value: 1 },
          ],
          rules: [
            {
              required: true,
              message: "请选择用户角色",
              trigger: "blur",
            },
          ],
        },
      ],
      adduserFromData: {
        username: "",
        nickname: "",
        cellphone: "",
        password: "",
        limits: 1,
      },
      edituserFromObj: [
        {
          input: true, //是input
          label: "登录名称", //字段
          prop: "username", //字段名
          width: 12, //参考el-col
          placeholder: "请输入登录名称",
          disabled: true, //是否禁用
          labelWidth: "80px",
        },
        {
          input: true, //是input
          label: "用户名称", //字段
          prop: "nickname", //字段名
          width: 12, //参考el-col
          placeholder: "请输入用户名称",
          disabled: false, //是否禁用
          labelWidth: "80px",
          rules: [
            {
              required: true,
              message: "请输入用户名称",
              trigger: "blur",
            },
          ],
        },
        {
          input: true, //是input
          label: "手机号", //字段
          prop: "cellphone", //字段名
          width: 12, //参考el-col
          placeholder: "请输入手机号",
          disabled: false, //是否禁用
          labelWidth: "80px",
          rules: [
            {
              required: true,
              message: "请输入手机号",
              trigger: "blur",
              validator: validateTel,
            },
          ],
        },
        {
          select: true,
          label: "用户角色",
          prop: "limits",
          placeholder: "请选择用户角色",
          width: 12, //参考el-col
          disabled: false,
          clearable: true, //是否清空
          labelWidth: "80px",
          options: [
            { label: "管理员", value: 0 },
            { label: "普通用户", value: 1 },
          ],
          rules: [
            {
              required: true,
              message: "请选择用户角色",
              trigger: "blur",
            },
          ],
        },
      ],
      edituserFromData: {
        username: "",
        nickname: "",
        cellphone: "",
        limits: 1,
      },
      updatePasswordFromObj: [
        {
          input: true, //是input
          label: "登录名称", //字段
          prop: "username", //字段名
          width: 24, //参考el-col
          placeholder: "请输入登录名称",
          disabled: true, //是否禁用
          labelWidth: "80px",
        },
        {
          input: true, //是input
          label: "旧密码", //字段
          prop: "oldPassword", //字段名
          width: 24, //参考el-col
          placeholder: "请输入旧的密码",
          disabled: false, //是否禁用
          labelWidth: "80px",
          rules: [
            {
              required: true,
              message: "请输入新密码",
              trigger: "blur",
            },
          ],
        },
        {
          input: true, //是input
          label: "新密码", //字段
          prop: "newPassword", //字段名
          width: 24, //参考el-col
          placeholder: "请输入新的密码",
          disabled: false, //是否禁用
          labelWidth: "80px",
          rules: [
            {
              required: true,
              message: "请输入新密码",
              trigger: "blur",
            },
            {
              validator: validateNewPassword,
              trigger: "change",
            },
          ],
        },
      ],
      updatePasswordFromData: {
        username: "",
        oldPassword: "",
        newPassword: "",
      },
      destroyed: true,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    addUser() {
      this.addUserDialogVisible = true;
    },
    editUser(row) {
      this.editUserDialogVisible = true;
      this.edituserFromData.nickname = row.nickname;
      this.edituserFromData.cellphone = row.cellphone;
      this.edituserFromData.username = row.username;
      this.edituserFromData.limits = row.limits;
    },
    delectUser(id) {
      //console.log("删除用户", id);
      this.$confirm(
        `将要删除登录名为:${id.username}的用户吗？是否确定删除?`,
        "删除用户",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let newMsg = {
            webMsgType: 1005,
            funCode: 2,
          };
          newMsg.data = { username: id.username };
          publishMsg(newMsg);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    updateUserPassword(username) {
      this.updateUserDialogVisible = true;
      this.updatePasswordFromData.username = username.username;
    },
    updateUserConfirm() {
      if (this.$refs.updateForm.submitForm()) {
        let newMsg = {
          webMsgType: 1005,
          funCode: 4,
        };
        for (let i = 0; i < 3; i++) {
          this.updatePasswordFromData.oldPassword = md5(
            this.updatePasswordFromData.oldPassword
          );
        }
        // 将最终密码解密
        this.updatePasswordFromData.oldPassword = Base64.encode(
          this.updatePasswordFromData.oldPassword
        );
        for (let i = 0; i < 3; i++) {
          this.updatePasswordFromData.newPassword = md5(
            this.updatePasswordFromData.newPassword
          );
        }
        // 将最终密码解密
        this.updatePasswordFromData.newPassword = Base64.encode(
          this.updatePasswordFromData.newPassword
        );
        newMsg.data = this.updatePasswordFromData;
        publishMsg(newMsg);
        this.updateUserDialogVisible = false;
      }
    },
    updateUserDialogClose() {
      this.$refs.updateForm.resetForm();
    },
    editUserConfirm() {
      if (this.$refs.editForm.submitForm()) {
        let newMsg = {
          webMsgType: 1005,
          funCode: 3,
        };
        newMsg.data = this.edituserFromData;
        publishMsg(newMsg);
        this.editUserDialogVisible = false;
      }
    },
    editUserDialogClose() {
      this.$refs.editForm.resetForm();
    },

    onMessage(topic, msg) {
      switch (msg.webMsgType) {
        case 1005:
          {
            switch (msg.funCode) {
              case 0:
                if (msg.retCode != 0 || !msg.data) {
                  this.$message.error(msg.retMsg);
                } else {
                  this.TableList = msg.data;
                  this.loadingShow = false;
                }
                break;
              case 1:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    this.$message.error(msg.retMsg);
                  } else {
                    this.$message.success("添加用户成功");
                  }
                }

                break;
              case 2:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    this.$message.error(msg.retMsg);
                  } else {
                    this.$message.success("删除用户成功");
                  }
                }
                break;
              case 3:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    this.$message.error(msg.retMsg);
                  } else {
                    this.$message.success("修改用户信息成功");
                  }
                }
                break;
              case 4:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    this.$message.error(msg.retMsg);
                  } else {
                    this.$message.success("修改用户密码成功");
                  }
                }
                break;
              case 5:
                if (msg.retCode != 0 || !msg.data) {
                  this.$message.error(msg.retMsg);
                } else {
                  for (let i = 0; i < this.TableList.length; i++) {
                    if (this.TableList[i].username === msg.data.username) {
                      this.TableList[i].username = msg.data.username;
                      this.TableList[i].isLogin = msg.data.isLogin;
                      this.TableList[i].lastLogin = msg.data.lastLogin;
                      this.TableList[i].lastLogout = msg.data.lastLogout;
                    }
                  }
                }
                break;
              default:
                break;
            }
          }
          break;
        default:
          break;
      }
    },

    addUserConfirm() {
      if (this.$refs.addForm.submitForm()) {
        let ojj = {
          webMsgType: 1005,
          funCode: 1,
        };
        //将密码进行三次加密
        for (let i = 0; i < 3; i++) {
          this.adduserFromData.password = md5(this.adduserFromData.password);
        }
        //将最终密码解密
        this.adduserFromData.password = Base64.encode(
          this.adduserFromData.password
        );
        ojj.data = this.adduserFromData;
        publishMsg(ojj);
        this.addUserDialogVisible = false;
        this.$message.success("添加用户信息成功");
      }
    },
    addUserDialogClose() {
      this.$refs.addForm.resetForm();
    },
    // inpuit变化
    inputINPUT(value, index, prop) {},
    // inpuit Change
    inputChange(value, index, prop) {},
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    setMessageCallback(this.onMessage);
    publishMsg({
      webMsgType: 1005,
      funCode: 0,
    });
    this.loadingShow = true;
    //console.log("用户管理页面请求消息 完成");
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  beforedestroy() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  destroyed() {
    removeMessageCallback(this.onMessage);
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 5px 5px 5px 5px;
}
</style>
